import { isArray, isNullOrEmpty, isObject, isSetObject, isString } from './is'
import { tabPageList } from '../config'
import navigationConfig from '@/components/al-navigation/config'
import { apiHost } from '@/config';
import { useUserStoreWithOut } from '@/store/modules/user';

// 获取应用ID
export function $getPublishedApplicationId(): number {
    try {
      let applicationId = import.meta.env.VITE_APP_ID;
      if (applicationId) {
        const applicationIds = applicationId.split('h5_');
        if(applicationIds && applicationIds.length > 0){
          return Number(applicationIds[1])
        }
      }
    } catch (e) {
        return 0
    }
}

/**
 * 数组/对象遍历
 * @param object 要遍历的对象
 * @param formatCallback 要执行的方法
 */
export function $each<T = any>(
    object: Array<T> | Record<string, T> | Set<T>,
    formatCallback: (item: T, index?: number | string) => void
) {
    let index: number | string | T = 0
    if (isArray<T>(object)) {
        // Object 没有length, 只有 Array 有
        const { length } = object
        for (; index < length; index++) {
            formatCallback(object[index], index)
        }
    } else if (isSetObject<T>(object)) {
        for (index of object) {
            formatCallback(index)
        }
    } else if (isObject<T>(object)) {
        for (index in object) {
            formatCallback(object[index], index)
        }
    }
}

/**
 * 持久化信息
 * @param key 存储的key
 * @param content 存储的内容
 */
export function localSave(key: string, content: any, expire?: DateConstructor) {
    const _expire = expire ? expire : Date.now() + 1000 * 60 * 60 * 8;
    uni.setStorageSync(
        key,
        JSON.stringify({
            expire: _expire,
            value: content
        })
    )
}

/**
 * 获取持久化信息
 * @param key 存储的key
 */
export function localGet(key: string) {
    try {
        const result = JSON.parse(uni.getStorageSync(key) || '{}')
        if (result.hasOwnProperty('value')) {
            return result.value
        } else {
            return result
        }
    } catch (error) {
        return
    }
}

/**
 * 通用 Storage 存储
 * @param dataKey 存储的key
 * @param value 存储的内容，标准JSON对象
 * @returns {boolean} 存储是否成功
 */
export function setStorage(dataKey: string, value: any) {
    try {
        return uni.setStorageSync(dataKey, JSON.stringify(value))
    } catch (error) {
        return false
    }
}
/*
 * 获取存储内容
 * @param dataKey 存储的key
 * @returns {any} 存储的对象
 */
export function getStorageByKey(dataKey: string) {
    try {
        const data = uni.getStorageSync(dataKey)
        if (!isNullOrEmpty(data)) {
            return JSON.parse(data as string)
        }
        return null
    } catch (error) {
        return null
    }
}
/**
 * 处理页面跳转
 * @param {String} href 目标URL
 */
// export function handleRedirect(href: string) {
//     console.log(href);
    
//     const router = uni.$Router;
//     console.log(router);
    
//     // 提取URL部分
//     const pureURL = href.split('?')[0]
//     const isLeftNavigation = navigationConfig && navigationConfig.position && navigationConfig.position === 'left'
//     if (tabPageList.includes(pureURL) && !isLeftNavigation) {
//         uni.switchTab({
//             url: pureURL
//         })
//     } else {
//         router.push(href).catch((error) => {
//             uni.navigateTo({ url: '/pages/NoPage/NoPage' });
//             console.warn(error);
//         })
//     }
// }
export function handleRedirect(href: string) {
  const router = uni.$Router;
  const pureURL = href.split('?')[0];
  const isLeftNavigation =
    navigationConfig && navigationConfig.position && navigationConfig.position === 'left';

  if (tabPageList.includes(pureURL) && !isLeftNavigation) {
    uni.switchTab({ url: pureURL });
  } else {
    // ✅ 本地调试时 $Router 可能未注入，直接使用 navigateTo
    if (!router || !router.push) {
      console.warn('[handleRedirect] uni.$Router 未定义，本地调试使用 navigateTo 兜底');
      uni.navigateTo({ url: href });
      return;
    }

    router.push(href).catch((error) => {
      uni.navigateTo({ url: '/pages/NoPage/NoPage' });
      console.warn(error);
    });
  }
}

/**
 * 处理页面跳转
 * @param {String} href 目标URL
 */
export function handleRedirectForNav(
  settingId: String,
  customUrl: String,
  settingType = 'PAGE_LIST',
) {
  const router = uni.$Router;
  const PREFIX_MAP = {
    PAGE_LIST: 'Page',
    FORM_LIST: 'Form',
  };
  const url = customUrl
    ? customUrl
    : `/pages/${PREFIX_MAP[settingType]}${settingId}/${PREFIX_MAP[settingType]}${settingId}`;
  router.replace(url);
}

/**
 * 获取PC与移动端产品ID映射map
 * 暂时简单使用uni.request，后续boss映射开发后可去掉(小程序不可使用fetch调用)
 */
export async function getProductIdMap() {
    return new Promise((resolve, reject) => {
        uni.request({
            url: `${apiHost}/productIdMap.json`,
            dataType: 'json',
            method: 'GET',
            success: res => {
                if(typeof res.data === 'string') {
                  // 尝试将parse为json对象
                  try{
                    resolve(JSON.parse(res.data))
                  }catch (e) {
                    resolve(res.data)
                  }
                } else {
                  resolve(res.data)
                }
            },
            fail: err => {
                reject(err)
            }
        })
    })
}

/**
 * 判断是否有权限
 */
export function permission(permissionVal: string | number) {
    const userStore = useUserStoreWithOut();
    const permissionCodeMap: string[] = userStore.getPermissionCodeMap || [];
    return permissionCodeMap.some((item) => item.includes(String(permissionVal)));
}

/**
 * 封装Json.parse
 * @param {string} str
 * @returns {Object}
 */
export function parseJson(str: string): Object {
  if (!isString(str)) {
    return str;
  }
  try {
    return JSON.parse(str);
  } catch (error) {
    console.log(error);
    return str;
  }
}
